package com.csi.sai.servlet;

import java.io.IOException;
import java.util.ArrayList;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.sql.DataSource;

import org.omg.PortableInterceptor.SUCCESSFUL;

import com.csi.sai.bl.dataview.GetDataView;
import com.csi.sai.bl.dataview.GetDataViewFactory;
import com.csi.sai.bl.demand.DemandProcess;
import com.csi.sai.data.entities.Cliente;
import com.csi.sai.data.entities.Contacto;
import com.csi.sai.data.entities.Demand;
import com.csi.sai.utilities.Constants;
import com.csi.sai.utilities.SystemMessages;
import com.csi.sai.utilities.Utilities;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

/**
 * Servlet implementation class DemandServlet
 */
@WebServlet("/web/DemandServlet")
public class DemandServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private InitialContext envContext;
	private DataSource ds;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public DemandServlet() {
        super();
        try {
			envContext = new InitialContext();
			Context initContext = (Context) envContext.lookup("java:/comp/env");
			ds = (DataSource) initContext.lookup("SAIDB");
			System.out.println("Data source obteined");
		} catch (NamingException e) {
			e.printStackTrace();
		}
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		JSONObject jsonResponse = new JSONObject();
		JSONObject jsonRequest = JSONObject.fromObject(request.getParameter("jsonReq"));
		DemandProcess demandProcess = new DemandProcess(ds);
		boolean succesfully = false;
		String process = jsonRequest.getString("process");
		if(process.equals(Constants.PROCESS_SELECTS)) {
			int type = jsonRequest.getInt("type");
			int id = jsonRequest.getInt("idCliente");
			succesfully = demandProcess.loadSelects(type, Utilities.getUserFromSession(request), id, true, new Demand());
			if(succesfully){
				jsonResponse.put("Flag", "true");
				jsonResponse.put("combo", demandProcess.getHTMLCode());
			} else {
				jsonResponse.put("Flag", "false");
				jsonResponse.put("Error", SystemMessages.getErrorMessage());
			}
		} else if(process.equals(Constants.PROCESS_CREATEDEMAND)) {
			Demand demand = loadDemandFromJSON(jsonRequest);
			int type = jsonRequest.getInt("type");
			succesfully = demandProcess.catalogDemand(demand, type);
			if(succesfully) { 
				jsonResponse.put("Flag", "true");
				jsonResponse.put("idGen", demandProcess.getIdGenerated());
			} else {
				jsonResponse.put("Flag", "false");
				jsonResponse.put("Error", SystemMessages.getErrorMessage());
			}
		} else if (process.equals(Constants.PROCESS_GETDEMANDby)) {
			ArrayList<String> paramList = getParamsFromJSON(jsonRequest);
			int editMode = jsonRequest.getInt("eMode");
			int type = 0;
			boolean eMode = editMode!=1; 
			if(editMode!=1) { type=jsonRequest.getInt("type"); }
			GetDataView dataView = GetDataViewFactory.getDataView(type, ds);
			succesfully = dataView.getDemandByFilters(paramList, eMode);
			if(succesfully) {
				jsonResponse.put("Flag", "true");
				if(editMode==1) {
					jsonResponse.put("demand", dataView.getDemand());
					jsonResponse.put("date",dataView.getDemand().getCreation());
					/** Trae combo vendedor **/
					demandProcess.loadSelects(1, Utilities.getUserFromSession(request), dataView.getDemand().getClient(), true, dataView.getDemand());
					jsonResponse.put("sales", demandProcess.getHTMLCode());
					
					/** Trae combo Cliente **/
					demandProcess.loadSelects(2, Utilities.getUserFromSession(request), dataView.getDemand().getClient(), true, dataView.getDemand());
					jsonResponse.put("client", demandProcess.getHTMLCode());
					
					/** Trae combo Contacto **/
					demandProcess.loadSelects(3, Utilities.getUserFromSession(request), dataView.getDemand().getClient(), true, dataView.getDemand());
					jsonResponse.put("contact", demandProcess.getHTMLCode());
					
					/** checked **/
					if(dataView.getDemand().getPriorityDate() != null) {
						jsonResponse.put("checked", true);
					}
					if(dataView.getDemand().isAvToTravel() != 0) {
						jsonResponse.put("travel", true);
					}
				} else {
					jsonResponse.put("Html", dataView.getCodeGenerated());
				}
			} else {
				jsonResponse.put("Flag", "false");
				jsonResponse.put("Error", SystemMessages.getErrorMessage());
			}
		} else if(process.equals(Constants.PROCESS_CREATECLIENT)) {
			Cliente client = getClientFormJSONObj(jsonRequest);
			client.setEstatus(Constants.STS_ACTIVE);
			client.setIdEmpleado(Utilities.getUserFromSession(request));
			int stype = jsonRequest.getInt("sType");
			int type = jsonRequest.getInt("type");
			succesfully = demandProcess.catalogClient(type, stype, client);
			if(succesfully) {
				jsonResponse.put("Flag", "true");
				/* REal */
				jsonResponse.put("idGenerated", demandProcess.getIdGenerated());
				jsonResponse.put("HTMLCode", demandProcess.getHTMLCode());
				
				/* Demo *
				jsonResponse.put("idGenerated", 23);
				jsonResponse.put("HTMLCode", Constants.DEMO);
				/**/
				
			} else {
				jsonResponse.put("Flag", "false");
			}
		} else if(process.equals(Constants.PROCESS_GETCLIENTby)) {
			Cliente client = getClientFormJSONObj(jsonRequest);
			client.setIdEmpleado(Utilities.getUserFromSession(request));
			GetDataView view = GetDataViewFactory.getDataView(6, ds);
			boolean editMode = jsonRequest.getString("eMode").equals("1");
			succesfully = view.createReportClientBy(2, editMode, client);
			if(succesfully) {
				jsonResponse.put("Flag", "true");
				if(editMode) {
					/**
					 * Se llena el objeto cliente
					 */
					Cliente clt = view.getCliente();
					jsonResponse.put("Id", clt.getIdCliente());
					jsonResponse.put("Nombre", clt.getNombre());
					jsonResponse.put("Direccion", clt.getDireccion());
					jsonResponse.put("Web", clt.getPaginaWeb());
					jsonResponse.put("HTMLCode", view.getCodeGenerated());
					
					/**
					 * Se obtienen los candidatos de este Cliente 
					 **/
					Contacto contact = new Contacto();
					contact.setIdCliente(clt.getIdCliente());
					view = GetDataViewFactory.getDataView(7, ds);
					succesfully = view.createReportContact(3, contact);
					if(succesfully) {
						jsonResponse.put("HTMLContacts", view.getCodeGenerated());
					}
					
				} else {
					jsonResponse.put("HTMLCode", view.getHTMLCode());
				}
			} else {
				jsonResponse.put("Flag", "false");
			}
		} else if(process.equals(Constants.PROCESS_GETCLIENTS)) {
			int type = Integer.parseInt(jsonRequest.getString("type"));
			succesfully = demandProcess.catalogClient(type, 0, new Cliente());
			if(succesfully) {
				jsonResponse.put("Flag", "true");
				jsonResponse.put("HTMLCode", demandProcess.getHTMLCode());
			} else {
				jsonResponse.put("Flag", "false");
			}
		} else if(process.equals(Constants.PROCESS_CREATECONTACT)) {
			int type = Integer.parseInt(jsonRequest.getString("type"));
			int stype = jsonRequest.getInt("sType");
			Contacto contacto = getContactFromJSONObj(jsonRequest);
			succesfully = demandProcess.catalogContact(type,stype, contacto);
			if(succesfully) {
				jsonResponse.put("Flag", "true");
				jsonResponse.put("HTMLCode", demandProcess.getHTMLCode());
			} else {
				jsonResponse.put("Flag", "false");
			}
		} else if(process.equals(Constants.PROCESS_GETCONTACTby)) {
			int type = jsonRequest.getInt("type");
			
			Contacto contact = getContactFromJSONObj(jsonRequest);
			GetDataView view = GetDataViewFactory.getDataView(7, ds);
			succesfully = view.createReportContact(type, contact);
			if(succesfully) {
				jsonResponse.put("Flag", "true");
				jsonResponse.put("name", view.getContact().getNombreContacto());
				jsonResponse.put("patt", view.getContact().getApellidoPaterno());
				jsonResponse.put("matt", view.getContact().getApellidoMaterno());
				jsonResponse.put("add",  view.getContact().getDireccion());
				jsonResponse.put("HTMLCode", view.getCodeGenerated());
			} else {
				jsonResponse.put("Flag", "false");
			}
		} else if(process.equals(Constants.PROCESS_REASSIGN)) {
			int demandToReassign = jsonRequest.getInt("idDemand");
			String comment = jsonRequest.getString("comment");
			int idEmployee = Utilities.getUserFromSession(request);
			succesfully = demandProcess.reassignDemand(3,demandToReassign, comment, idEmployee);
			if(succesfully) {
				jsonResponse.put("Flag", "true");
			}
		}
		
		/** Vista generica **/
		else if(process.equals(Constants.PROCESS_ADDCOMPONENT)) {
			String parent = jsonRequest.getString("parent");
			succesfully = demandProcess.getComponent(parent);
			if(succesfully) {
				jsonResponse.put("Flag", "true");
				jsonResponse.put("HTMLCode", demandProcess.getHTMLCode());
			}
		} 
		else if(process.equals(Constants.PROCESS_SELECTSTYPES)) {
			succesfully = demandProcess.getCombosClient();
			if(succesfully) {
				jsonResponse.put("Flag", "true");
				jsonResponse.put("HTMLCode", demandProcess.getHTMLCode());
			}
		}
		else if(process.equals(Constants.PROCESS_DELETEENTITIE)) {
			String dbID = jsonRequest.get("dbId").toString();
			String entitie = jsonRequest.get("entitie").toString();
			succesfully = demandProcess.deleteEntitie(dbID, entitie);
			if(succesfully) {
				jsonResponse.put("Flag", "true");
			}
		} 
		
		sendResponse(response, jsonResponse);
	}

	private Contacto getContactFromJSONObj(JSONObject jsonRequest) {
		Contacto contacto = new Contacto();
		contacto.setIdContacto(jsonRequest.getString("idContact").equals("") ? 0 : jsonRequest.getInt("idContact"));
		contacto.setIdCliente(jsonRequest.getString("idClient").equals("") ? 0 : jsonRequest.getInt("idClient"));
		contacto.setNombre(jsonRequest.getString("name"));
		contacto.setApellidoPaterno(jsonRequest.getString("paterno"));
		contacto.setApellidoMaterno(jsonRequest.getString("materno"));
		contacto.setDireccion(jsonRequest.getString("address"));
		contacto.setTelefono(Utilities.getDataFromArrayObject(jsonRequest.getJSONArray("aPhone")));
		contacto.setCorreo(Utilities.getDataFromArrayObject(jsonRequest.getJSONArray("aMail")));
		
		contacto.setEditMode(jsonRequest.getInt("eMode")==1?true:false);
		return contacto;
	}

	private Cliente getClientFormJSONObj(JSONObject jsonRequest) {
		Cliente cliente = new Cliente();
		cliente.setIdCliente(jsonRequest.getString("id").equals("") ? 0 : jsonRequest.getInt("id"));
		cliente.setNombre(jsonRequest.getString("nombre"));
		cliente.setDireccion(jsonRequest.getString("direccion"));
		cliente.setPaginaWeb(jsonRequest.getString("pagina"));
		cliente.setEstatus(jsonRequest.getString("estatus"));
		cliente.setCorreo(Utilities.getDataFromArrayObject(jsonRequest.getJSONArray("mail")));
		cliente.setTelefono(Utilities.getDataFromArrayObject(jsonRequest.getJSONArray("telefono")));
		cliente.setTecnologia(Utilities.getDataFromArrayObject(jsonRequest.getJSONArray("tech")));
		
		return cliente;
	}
	
	private ArrayList<String> getParamsFromJSON(JSONObject jsonRequest) {
		ArrayList<String> listParams = new ArrayList<>();
		listParams.add(jsonRequest.getString("client").equals("") ? "0" : jsonRequest.getString("client"));
		listParams.add(jsonRequest.getString("salesperson").equals("") ? "0" : jsonRequest.getString("salesperson"));
		listParams.add(jsonRequest.getString("vacancy"));
		listParams.add(jsonRequest.getString("status"));
		listParams.add(jsonRequest.getString("initial"));
		listParams.add(jsonRequest.getString("finished"));
		listParams.add(jsonRequest.getString("id"));
		
		return listParams;
	}

	private Demand loadDemandFromJSON(JSONObject jsonObject) {
		Demand demand = new Demand();
		
		demand.setIdDemand(Integer.parseInt(jsonObject.getString("idDemand")));
		demand.setContact(jsonObject.getString("contact"));
		demand.setVacancy(jsonObject.getString("vacancy"));
		demand.setProfile(jsonObject.getString("profile"));
		demand.setCreation(jsonObject.getString("creationDate"));
		demand.setDuration(Integer.parseInt(jsonObject.getString("duration")));
		demand.setFinshDate(Utilities.getNextDateFromADate(demand.getCreation(), demand.getDuration()));
		demand.setMensualRate(Integer.parseInt(jsonObject.getString("rate")));
		demand.setIdSalesperson(Integer.parseInt(jsonObject.getString("salesperson")));
		demand.setClient(Integer.parseInt(jsonObject.getString("client")));
		demand.setNumVacancy(Integer.parseInt(jsonObject.getString("novacancy")));
		demand.setPipeLine(demand.getMensualRate()*demand.getDuration());
		demand.setAuthorization(Utilities.getTodayByFormat(Utilities.formatDB));
		String isPriority = jsonObject.getString("priorityCheck");
		if(isPriority.equals("true")) {
			demand.setPriorityDate(Utilities.getTodayByFormat(Utilities.formatDB));
		}
		/** Agregados 07-01-2013 **/
		demand.setExperience(jsonObject.getString("experiencia"));
		demand.setRequest(jsonObject.getString("req"));
		demand.setResidence(jsonObject.getString("residencia"));
		demand.setLenguaje(jsonObject.getString("lenguaje"));
		if(jsonObject.getString("viajar")=="true") {
			demand.setAvToTravel(1);
		}
		return demand;
	}

	public void sendResponse(HttpServletResponse response, JSONObject jsonResponse) throws IOException {
		response.setContentType("text/xml; charset=iso-8859-1");
		response.setHeader("Cache-Control", "no-cache");
		response.getWriter().print(jsonResponse);
	}
}
